﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UIWindow.Attributes;
using UIWindow.Lucifer;

namespace UIWindow.Domains
{
    public class TaskManager
    {
        private static ConcurrentDictionary<string, object> _taskcd = new ConcurrentDictionary<string, object>();
        private static IObjectContainer _objectContainer;
        static TaskManager()
        {
            _objectContainer = Bootstrapper.GetContainer();
        }

        public static void Publish<T>(T context) where T : IDataContext, new()
        {
            string key = $"{context.Types.GetHashCode()}{context.AddressSignal}{context.AddressComplete}";
            if (_taskcd.ContainsKey(key) || !_taskcd.TryAdd(key, context)) return;
            var obj = _objectContainer.ResolveEvent(context.GetType());
            MethodInfo method = obj.GetType().GetMethod("Handle");
            Task.Run(new Action(() => method?.Invoke(obj, new object[] { context })));
        }

        public static bool RemoveTask<T>(T context) where T : IDataContext, new()
        {
            string key = $"{context.Types.GetHashCode()}{context.AddressSignal}{context.AddressComplete}";
            if (_taskcd.TryRemove(key, out _)) return true;
            return false;
        }

        /// <summary>
        /// 移除所有任务
        /// </summary>
        public static void RemoveAll() => _taskcd.Clear();
    }
}
